package cn.itcast.itcaststore.web.servlet.client;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.itcaststore.domain.User;
import cn.itcast.itcaststore.exception.LoginException;
import cn.itcast.itcaststore.service.UserService;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.鑾峰彇鐧诲綍椤甸潰杈撳叆鐨勭敤鎴峰悕涓庡瘑鐮�
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 2.璋冪敤service瀹屾垚鐧诲綍鎿嶄綔銆�
		UserService service = new UserService();
		try {
			User user = service.login(username, password);
			
			// 3.鐧诲綍鎴愬姛锛屽皢鐢ㄦ埛瀛樺偍鍒皊ession涓�.
			request.getSession().setAttribute("user", user);
			// 鑾峰彇鐢ㄦ埛鐨勮鑹诧紝鍏朵腑鐢ㄦ埛鐨勮鑹插垎鏅�氱敤鎴峰拰瓒呯骇鐢ㄦ埛涓ょ
			String role = user.getRole();
			// 濡傛灉鏄秴绾х敤鎴凤紝灏辫繘鍏ュ埌缃戜笂涔﹀煄鐨勫悗鍙扮鐞嗙郴缁燂紱鍚﹀垯杩涘叆鎴戠殑璐︽埛椤甸潰
			if ("瓒呯骇鐢ㄦ埛".equals(role)) {
				response.sendRedirect(request.getContextPath() + "/admin/login/home.jsp");
				return;
			} else {
				response.sendRedirect(request.getContextPath() + "/client/myAccount.jsp");
				return;
			}
		} catch (LoginException e) {
			// 濡傛灉鍑虹幇闂锛屽皢閿欒淇℃伅瀛樺偍鍒皉equest鑼冨洿锛屽苟璺宠浆鍥炵櫥褰曢〉闈㈡樉绀洪敊璇俊鎭�
			e.printStackTrace();
			request.setAttribute("register_message", e.getMessage());
			request.getRequestDispatcher("/client/login.jsp").forward(request, response);
			return;
		}
	}
}
